<?php
/**
 * PaymentHistoryModel
 * @author tuanna
 * @version 1.0
 */
require_once 'Zend/Db/Table/Abstract.php';

class PaymentHistoryModel extends Zend_Db_Table_Abstract
{
    protected $_name = 'payment_history';
   
    public function addMoney($month, $user_id, $amount){
    	//Check if record exist
    	$record = $this->getRecord($month, $user_id);
    	if(!$record){
			$data = array(
				'month' => $month,
				'user_id' => $user_id,
				'total_money' => $amount
			);
			$this->insert($data);
			return true;
    	
    	}else{
	    	$record_id = $record->id;
	    	$total_money = $record->total_money + $amount;
	    	$data = array('total_money' => $total_money);
	    	$this->update($data, "id = $record_id");
	    	return true;
    	}
    }
    
    public function addFee($month, $user_id, $fee){
    	//Check if record exist
    	$record = $this->getRecord($month, $user_id);
    	if(!$record){
			$data = array(
				'month' => $month,
				'user_id' => $user_id,
				'total_fee' => $fee
			);
			$this->insert($data);
			return true;
    	
    	}else{
	    	$record_id = $record->id;
	    	$total_fee = $record->total_fee + $fee;
	    	$data = array('total_fee' => $total_fee);
	    	$this->update($data, "id = $record_id");
	    	return true;
    	}
    }
    
    public function addOrderCount($month, $user_id, $order_num){
    	//Check if record exist
    	$record = $this->getRecord($month, $user_id);
    	if(!$record){
			$data = array(
				'month' => $month,
				'user_id' => $user_id,
				'order_count' => $order_num
			);
			$this->insert($data);
			return true;
    	
    	}else{
	    	$record_id = $record->id;
	    	$order_count = $record->order_count + $order_num;
	    	$data = array('order_count' => $order_count);
	    	$this->update($data, "id = $record_id");
	    	return true;
    	}
    }
    
    public function getRecord($month, $user_id){
    	$select = $this->select();
    	$select->where("month = ?", $month);
    	$select->where("user_id = ?", $user_id);
    	
    	$row = $this->fetchRow($select);
    	
    	return $row;
    }
    
    public function updateData($id, $data){
    	$check = $this->update($data, "id = $id");
    	
    	return $check;
    }
    
    public function deleteRecord($del_ids){
    	if($this->update(array('status' => 0), "id in ($del_ids)") > 0){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    public function getListRecord($search_key = "", $start_month = NULL, $end_month = NULL, $user_id = 0, $page = NULL, $line_per_page = NULL)
    {
    	$db = Zend_Registry::get('connectDB');
		$select = $db->select()
					->from(array('p'=>'payment_history'),array('id'=>'p.id','month' => 'p.month','user_id' => 'p.user_id', 'order_count' => 'p.order_count', 'total_money'=> "p.total_money", 'total_fee'=>"p.total_fee", 'status'=> 'p.status'))
					->joinLeft(array('u'=>'user'),'u.id = p.user_id',array('username'=>'u.username', 'name'=>'u.name', 'phone'=>"u.phone", 'email' => 'u.email', 'address' => 'u.address'));

		//search key
    	if($search_key){
    		$select->where("u.username like '%$search_key%' or u.email like '%$search_key%' or u.id like '%$search_key%' or u.phone like '%$search_key%'");
    	}		
		
		//filter by time
		if($start_month)
			$select->where("p.month >= ?", $start_month);
		if($end_month)
			$select->where("p.month <= ?", $end_month);
    	
		//filter by user_id
		if($user_id)
			$select->where("p.user_id = ?", $user_id);
    	$select->where('p.status = 1');
    	
    	//do paging
    	if($page && $line_per_page){
    		$select->limitPage($page, $line_per_page);
    	}
    	
    	//order
    	$select->order("p.month desc");
    	
    	$list = $db->fetchAll($select);
    	
    	return $list;
    }
    
    public function getListRecordCount($search_key = "", $start_month = NULL, $end_month = NULL, $user_id = 0, $page = NULL, $line_per_page = NULL)
    {
    	$db = Zend_Registry::get('connectDB');
		$select = $db->select()
					->from(array('p'=>'payment_history'),array('id'=>'p.id','month' => 'p.month','user_id' => 'p.user_id', 'order_count' => 'p.order_count', 'total_money'=> "p.total_money", 'total_fee'=>"p.total_fee", 'status'=> 'p.status'))
					->joinLeft(array('u'=>'user'),'u.id = p.user_id',array('username'=>'u.username', 'name'=>'u.name', 'phone'=>"u.phone"));

		//search key
    	if($search_key){
    		$select->where("u.username like '%$search_key%' or u.email like '%$search_key%' or u.id like '%$search_key%' or u.phone like '%$search_key%'");
    	}		
		
		//filter by time
		if($start_month)
			$select->where("p.month >= ?", $start_month);
		if($end_month)
			$select->where("p.month >= ?", $end_month);
    	
		//filter by user_id
		if($user_id)
			$select->where("p.user_id = ?", $user_id);
    	$select->where('p.status = 1');
    	
    	$list = $db->fetchAll($select);
    	
    	return count($list);
    }    	
    
  	public function fetchRecord($id){
    	$row = $this->fetchRow("id = $id and status = 1");
    	return $row;
    }
    
    /**
     * Calculate different rent unit (30 minutes)
     * @param $start_time
     * @param $end_time
     */
    public function calculateDiffRentUnit($start_time, $end_time){
    	Zend_Debug::dump("$start_time~$end_time");
    	$start_date = substr($start_time, 0, 10);
    	$start_time = substr($start_time, 11, 8);
    	$end_date = substr($end_time, 0, 10);
    	$end_time = substr($end_time, 11, 8);
    	
    	$diff_days= (strtotime($end_date) - strtotime($start_date)) / (60 * 60 * 24);
		
		//echo $start_time;
    	$start_hour = substr($start_time, 0, 2);
    	$start_minute = substr($start_time, 3, 2);
    	
    	$end_hour = substr($end_time, 0, 2);
    	$end_minute = substr($end_time, 3, 2);
    	
    	$rent_unit =  $diff_days * 48 + (($end_hour - $start_hour) * 2) + ($end_minute - $start_minute) / 30;
    	
    	return $rent_unit;	
    }
    
    /**
     * Return array contain money for each month
     * from start_time to end_time
     * @param $start_time
     * @param $end_time
     * @param $rent_price
     */
    public function calculateMoneyForMonths($start_time, $end_time, $price){
    	Zend_Loader::loadClass("UtinitiesModel");
    	
    	//prepare time data
    	$start_time_arr = UtinitiesModel::parseTimeString($start_time);
    	$end_time_arr = UtinitiesModel::parseTimeString($end_time);
    	
    	$datas = array();
    	
    	//calculate different months
    	$diff_months = UtinitiesModel::diffMonth($start_time, $end_time);
    	if($diff_months == 0){
    		$rent_unit = $this->calculateDiffRentUnit($start_time, $end_time);
    		$datas[$start_time_arr['year']. "-" . $start_time_arr['month']] = $rent_unit * $price;
    		
    	}else{
    		for ($i = 0; $i <= $diff_months; $i++){
    			$start = UtinitiesModel::addMonths($start_time_arr['year']."-".$start_time_arr['month'], $i);

    			//calculate start day of month
    			$base_time = substr($start, 0, 4) . "-01-01 00:00:00";
		    	$temp_start_time = strtotime ( '+ ' . (substr($start, 5, 2) - 1) . ' months' , strtotime ($base_time)) ;
				$temp_start_time = date ( 'Y-m-d H:i:s' , $temp_start_time);
    			
				//calculate end day of month
				$base_time = substr($start, 0, 4) . "-01-31 00:00:00";
		    	$temp_end_time = strtotime ( '+ ' . (substr($start, 5, 2) - 1) . ' months' , strtotime ($base_time)) ;
		    	$temp_end_time = date ( 'Y-m-d H:i:s' , $temp_end_time);
		    	
		    	$temp_start_time = $temp_start_time > $start_time ? $temp_start_time : $start_time;
		    	$temp_end_time = $temp_end_time < $end_time ? $temp_end_time : $end_time;
		    	
		    	$rent_unit = $this->calculateDiffRentUnit($temp_start_time, $temp_end_time);
				$datas[$start] = $rent_unit * $price;
    		}
    	}
    	
    	return $datas;
    }
    
    public function addMoneyForMonths($user_id, $start_time, $end_time, $price, $mode = "add"){
    	$payment_datas = $this->calculateMoneyForMonths($start_time, $end_time, $price);
    	
    	foreach ($payment_datas as $key=>$value){
    		if($mode == "add")
	    		$this->addMoney($key, $user_id, $value);
	    	else
	    		$this->addMoney($key, $user_id, -$value);
    	}
    }
    
	public function addFeeForMonths($user_id, $start_time, $end_time, $price, $mode = "add"){
    	$payment_datas = $this->calculateMoneyForMonths($start_time, $end_time, $price);
    	
    	foreach ($payment_datas as $key=>$value){
    		if($mode == "add")
	    		$this->addFee($key, $user_id, $value);
	    	else
	    		$this->addFee($key, $user_id, -$value);
    	}
    }
}